package reflection;

import cat.Cat;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author DCSGO
 * @version 1.0
 * 传统方式调用方法和反射
 * 机制调用方法效率对比与优化
 */
public class Reflection02 {
    public static void m1(int cnt) {
        long begin = System.currentTimeMillis();

        Cat cat = new Cat();
        for (int i = 0; i < cnt; i++) {
            cat.met();
        }

        long end = System.currentTimeMillis();
        System.out.println("m1耗时：" + (end - begin));
    }

    public static void m2(int cnt) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        long begin = System.currentTimeMillis();

        Class cls = Class.forName("cat.Cat");
        Object o = cls.newInstance();
        Method met = cls.getMethod("met");
        for (int i = 0; i < cnt; i++) {
            met.invoke(o);
        }

        long end = System.currentTimeMillis();
        System.out.println("m2耗时：" + (end - begin));
    }

    public static void m3(int cnt) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        long begin = System.currentTimeMillis();

        Class cls = Class.forName("cat.Cat");
        Object o = cls.newInstance();
        Method met = cls.getMethod("met");
        //true 表示反射对象在使用时应禁止Java语言访问检查 值 false 表示反射的对象应该强制执行Java语言访问检查
        met.setAccessible(true);//禁止访问检查 提示效率
        for (int i = 0; i < cnt; i++) {
            met.invoke(o);
        }

        long end = System.currentTimeMillis();
        System.out.println("m3耗时：" + (end - begin));
    }

    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        int cnt = Integer.MAX_VALUE;
        m1(cnt);
        m2(cnt);
        m3(cnt);
        //m1耗时：5
        //m2耗时：4637
        //m3耗时：3836
    }
}
